package fr.xebia.monitoring.export.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.VelocityException;

import fr.xebia.monitoring.beans.AggregatedMeasures;

public class MeasureViewerServlet extends AbstractMeasureAwareServlet {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = Logger.getLogger(MeasureViewerServlet.class);
	
	private VelocityContext context;
	private Template template;

	@Override
	public void init() throws ServletException {
		super.init();
		Properties properties = new Properties();
		ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
		InputStream inStream = contextClassLoader.getResourceAsStream("velocity.properties");
		if (inStream == null) {
			throw new ServletException("Can't find Velocity configuration file: velocity.properties");
		}
		try {
			properties.load(inStream);
			Velocity.init(properties);
			context = new VelocityContext();
			template = Velocity.getTemplate("measureViewer.html.vm");
		} catch (Exception e) {
			logger.error("Velocity initialization failed", e);
			throw new ServletException("Velocity initialization failed", e);
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		PrintWriter writer = resp.getWriter();
		printOutMeasure(writer);
	}

	private void printOutMeasure(Writer writer) throws ServletException, IOException {
		try {
			AggregatedMeasures measures = getAggregatedMeasures();
			context.put("measureList", measures.getAggregatedMeasure());
//			Writer writer = new OutputStreamWriter(outputStream);
//			Writer writer = new StringWriter();
			template.merge(context, writer);
//			System.out.println(writer.toString());
		} catch (VelocityException e) {
			throw new ServletException("Can't generate HTML output", e);
		}
	}
}
